<template lang="pug">
mt-dialog(
  v-model="appmodel"
  cancel-text="取消"
  confirm-text="打印"
  title="条码打印"
  :on-close="updateModel"
  :on-cancel="updateModel"
  :on-confirm="printBarcode"
  size="small"
)
  div
    img(v-for="(item,index) in barcodeList" :src="item" :key="index" style="margin-left: 15px;")
</template>

<script setup lang="ts">
import { useApi } from "@scmt/core-api";
import { type SpecimenEntity } from "@scmt/api-lis-specimen";
import { useRequest } from "@scmt/common-hooks";
import { getLodop } from "./LodopFuncs";
import { ESpecimenStatus } from "@scmt/api-common";
//添加 Props属性
const props = defineProps({
  selectionRow: {
    type: Array as PropType<SpecimenEntity[]>,
    default: () => [],
  },
  barcodeData: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
});
const $api = useApi();
const barcodeList = ref([]);

const appmodel = defineModel({
  default: false,
});
const emit = defineEmits(["message-to-parent"]);
const updateModel = () => {
  appmodel.value = false;
};

const { request, loadingMap } = useRequest({
  batchGenerateBarcode: (q: any) => {
    return $api.lis.specimen.batchGenerateBarcode(q);
  },
  printBarcode: (val: SpecimenEntity[]) => {
    return $api.lis.specimen.printBarcode(val).then((res) => {
      if (res) {
        barcodeList.value = res.datalist;
      }
    });
  },
});

const printBarcode = () => {
  let LODOP = getLodop();
  LODOP.PRINT_INIT("条码打印"); //打印初始化
  LODOP.SET_PRINT_PAGESIZE(0, "500", "300", ""); //设定纸张大小

  for (let i = 0; i < barcodeList.value.length; i++) {
    LODOP.ADD_PRINT_IMAGE(20, -15, "100%", "100%", barcodeList.value[i]);
    if (i + 1 != barcodeList.value.length) {
      LODOP.NEWPAGE(); //分页
    }
  }
  const specimenIdData = [].concat(props.selectionRow).map((item) => {
    return item.id;
  });
  request("batchGenerateBarcode", {
    specimenList: specimenIdData,
    status: ESpecimenStatus.PrintedBarCode,
  });
  emit("message-to-parent");
  LODOP.PREVIEW(); //预览打印
};

watch(
  appmodel,
  (visible: boolean) => {
    if (visible) {
      barcodeList.value = [];
      if (props.barcodeData && props.barcodeData.length > 0) {
        barcodeList.value = props.barcodeData;
      } else if (props.selectionRow) {
        request("printBarcode", props.selectionRow);
      }
    }
  },
  {
    immediate: true,
  }
);
</script>
